import fs from 'fs';

import iconv from 'iconv-lite';

const getSizeString = (()=>{
  const unitSizes = new Array(12).fill(0).map((v, i)=> 1024 ** i);
  const units = ['B', 'KB', 'MB', "GB", "TB", "PB", "EB", "ZB", "YB", "BB", "NB", "DB"];
  
  return function getSizeString(size) {
    let unit;
    let unitSize;
    for (let i = 0, length = unitSizes.length; i < length; i++) {
      if(size <= unitSizes[i]) {
        unit = units[i - 1];
        unitSize = unitSizes[i - 1];
        break;
      }
    }
    return unit === 'B' ? size + unit : (size / unitSize).toFixed(2) + unit;
  }
})();

const fileContent = iconv.decode(fs.readFileSync('./maps.ini'), 'gbk');

// 获取文件每一行并且删除所有无效的分割后的元素
let rows = fileContent.split(/[\r\n]/).filter(v => v || false);

// 去头并且获取头
const head = rows.shift();
// 去尾并且获取尾部
const tail = rows.pop();

// 遍历并处理每一行
let mapFileInfosAll = rows.map(v => {
  // 分割地图hash和标题
  const [hash, title] = v.split('=');
  return {
    hash,
    title
  };
});

const maps = new Map();

mapFileInfosAll.forEach((mapFileInfos) => {
  // files代表单地图多个文件
  const mapFilesInfos = maps.get(mapFileInfos.title);
  if (mapFilesInfos) {
    mapFilesInfos.push(mapFileInfos);
  } else {
    maps.set(mapFileInfos.title, [mapFileInfos]);
  }
});

// 遍历并且读取文件状态
maps.forEach((map, key) => {
  const mapFilesInfos = map;
  mapFilesInfos.forEach((mapFileInfos) => {
    const filename = `${mapFileInfos.hash}.w3x`;
    mapFileInfos.filename = filename;
    mapFileInfos.stat = fs.existsSync(filename) && fs.statSync(filename);
  });
  // 过滤不存在的文件
  maps.set(key, mapFilesInfos.filter(v => v ? true : false));
});

// 排序之后的maps
const sortedMaps = new Map();

// 给maps排序
maps.forEach((value, key) => {
  const sortedFilesInfos = value.sort((a, b) => b.stat.ctime - a.stat.ctime);
  sortedMaps.set(key, sortedFilesInfos);
});

function connectPromise(promiseArrFn) {
	return promiseArrFn.reduce((o, n)=> {
		return o.then(n, n);
	}, Promise.resolve());
}

// 总删除数量和总大小
let deleteCount = 0;
let deleteSize = 0;
let actionsArrays = [];
sortedMaps.forEach((value, key) => {
  const mapFilesInfos = value;
  // 删除首个，也就是时间最靠前那个
  mapFilesInfos.shift();
  // 删除剩余所指向的文件，即为老版本文件，直接删除
  const actions = mapFilesInfos.filter((map)=> {
    return fs.existsSync(map.filename);
  }).map((map) => {
    return ()=> {
      return fs.promises.unlink(map.filename).then(v=> {
        console.log(`地图删除成功 - 地图：${map.title} 地图文件：${map.filename}`);
        deleteCount++;
        deleteSize += map.stat.size;
        // 从信息中删除
        
        mapFileInfosAll.splice(mapFileInfosAll.findIndex((info)=> info.hash === map.hash), 1);
        return;
      }).catch((err) => {
        if (err) {
          console.log(`Error：地图删除失败 - 地图：${map.title} 地图文件：${map.filename} detail: ${err}`);
        }
        return;
      });
    }
  });
  actionsArrays.push(actions);
});

const actions = actionsArrays.flat();
connectPromise(actions).then(v=> {
  console.log(`总共删除了： ${deleteCount} 个文件`);
  console.log(`总计清理硬盘空间 ${getSizeString(deleteSize)}`);
  // 更新maps.ini
  const mapsIniFileContent = head + '\r\n' + mapFileInfosAll.map(v=> `${v.hash}=${v.title}`).join('\r\n')  + '\r\n' + tail;
  fs.writeFileSync('./maps.ini', iconv.encode(mapsIniFileContent, 'gbk'));
  console.log('运行完成，您可以关闭窗口了');
});

new Promise(r=>setTimeout(r, 10000000));